package com.ruoyi.project.comp.home;

import cn.hutool.core.collection.CollectionUtil;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.comp.comment.service.ICompCommentService;
import com.ruoyi.project.comp.like.domain.CompLike;
import com.ruoyi.project.comp.like.service.ICompLikeService;
import com.ruoyi.project.comp.share.domain.CompShare;
import com.ruoyi.project.comp.share.service.ICompShareService;
import com.ruoyi.project.comp.work.domain.CompWork;
import com.ruoyi.project.comp.work.service.ICompWorkService;
import com.ruoyi.project.system.user.domain.User;
import com.ruoyi.project.system.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 作品评论Controller
 * 
 * @author ruoyi
 * @date 2025-11-02
 */
@Controller
@RequestMapping("/home")
public class HomeindexController extends BaseController
{

    @Autowired
    private ICompWorkService compWorkService;

    @Autowired
    private ICompLikeService compLikeService;

    @Autowired
    private IUserService userService;

    @Autowired
    private ICompShareService compShareService;


    @GetMapping("/login")
    @ResponseBody
    public AjaxResult login( HttpServletRequest request) {
        // 步骤5：用户信息存入Session，用于后续操作
        User user = new User();
        user.setUserId(1L);
        request.getSession().setAttribute("loginUser", user);
        return AjaxResult.success(user);
    }



    /**
     * 获取统计数据
     */
    @GetMapping("/stats")
    @ResponseBody
    public StatsDTO getStats() {
        StatsDTO stats = new StatsDTO();
        int userCount = 0;
        int compLikeCount = 0;
        int workCount = 0;
        int compShareCount = 0;


        User queryUser = new User();
        queryUser.setDelFlag(String.valueOf(0));
        List<User> userList = userService.selectUserList(queryUser);
        if(CollectionUtil.isNotEmpty(userList)){
            userCount = userList.size();
        }
//        List<CompLike> compLikeList = compLikeService.selectCompLikeList(new CompLike());
//        if(CollectionUtil.isNotEmpty(compLikeList)){
//            compLikeCount = compLikeList.size();
//        }
        CompWork queryCompWork = new CompWork();
        queryCompWork.setStatus(1L);
        List<CompWork> workList = compWorkService.selectCompWorkList(queryCompWork);
        if(CollectionUtil.isNotEmpty(workList)){
            workCount = workList.size();
        }
//        List<CompShare> compShareList = compShareService.selectCompShareList(new CompShare());
//        if(CollectionUtil.isNotEmpty(compShareList)){
//            compShareCount = compShareList.size();
//        }

        long workUserCount = 0L;
        if (CollectionUtil.isNotEmpty(workList)) {
            workUserCount = workList.stream()
                    .map(CompWork::getParticipantUserId)
                    .filter(Objects::nonNull)
                    .collect(Collectors.toSet())        // 收集到 Set 自动去重
                    .size();

            compLikeCount = workList.stream()
                    .map(CompWork::getLikeCount)
                    .filter(Objects::nonNull)  // 过滤掉null值
                    .mapToInt(Integer::intValue)  // 转换为IntStream
                    .sum();

            compShareCount = workList.stream()
                    .map(CompWork::getLookCount)
                    .filter(Objects::nonNull)  // 过滤掉null值
                    .mapToInt(Integer::intValue)  // 转换为IntStream
                    .sum();
        }


        stats.setTotalContestants((int) workUserCount);
        stats.setTotalUsers(userCount);
        stats.setTotalLikes(compLikeCount);
        stats.setTotalViews((long) compShareCount);
        return stats;
    }

    /**
     * 获取综合得分TOP10
     */
    @GetMapping("/rank/comprehensive")
    @ResponseBody
    public List<RankDTO> getComprehensiveRank() {
        List<RankDTO> list = new ArrayList<>();
//        list.add(new RankDTO(1, "红色记忆", 96.5));
//        list.add(new RankDTO(2, "党的光辉历程", 94.2));
//        list.add(new RankDTO(3, "革命精神永流传", 92.8));
//        list.add(new RankDTO(4, "红色家书", 91.5));
        // 可继续添加第5-10名数据
        CompWork queryCompWork = new CompWork();
        queryCompWork.setStatus(1L);
        List<CompWork> workList = compWorkService.selectCompWorkList(queryCompWork);
        workList = workList.stream()
                .sorted(Comparator.comparing(CompWork::getTotalScore ,
                                Comparator.nullsLast(Comparator.reverseOrder()))
                        .thenComparing(CompWork::getId)) // 得分相同时，按ID排序（可选）
                .limit(10) // 取前10条
                .collect(Collectors.toList()); // 转换为 List


        for (int i = 0; i < workList.size(); i++) {
            CompWork compWork = workList.get(i);
            RankDTO rankDTO = new RankDTO();
            rankDTO.setRank(i+1);
            if(compWork != null && compWork.getTotalScore() != null){
                rankDTO.setScore(compWork.getTotalScore().doubleValue());
            }else{
                rankDTO.setScore(0.0);
            }
            rankDTO.setTitle(compWork.getWorkName());
            list.add(rankDTO);
        }

        return list;
    }

    /**
     * 获取学生评分TOP10
     */
    @GetMapping("/rank/student")
    @ResponseBody
    public List<RankDTO> getStudentRank() {
        List<RankDTO> list = new ArrayList<>();
//        list.add(new RankDTO(1, "红色记忆", 95.8));
//        list.add(new RankDTO(2, "党的光辉历程", 93.5));
//        list.add(new RankDTO(3, "革命精神永流传", 92.1));
//        list.add(new RankDTO(4, "红色家书", 90.7));
        // 可继续添加第5-10名数据
        CompWork queryCompWork = new CompWork();
        queryCompWork.setStatus(1L);
        List<CompWork> workList = compWorkService.selectCompWorkList(queryCompWork);
        workList = workList.stream()
                .sorted(Comparator.comparing(CompWork::getStudentScore ,
                                Comparator.nullsLast(Comparator.reverseOrder()))
                        .thenComparing(CompWork::getId)) // 得分相同时，按ID排序（可选）
                .limit(10) // 取前10条
                .collect(Collectors.toList()); // 转换为 List


        for (int i = 0; i < workList.size(); i++) {
            CompWork compWork = workList.get(i);
            RankDTO rankDTO = new RankDTO();
            rankDTO.setRank(i+1);
            if(compWork != null && compWork.getTotalScore() != null){
                rankDTO.setScore(compWork.getTotalScore().doubleValue());
            }else{
                rankDTO.setScore(0.0);
            }
            rankDTO.setTitle(compWork.getWorkName());
            list.add(rankDTO);
        }
        return list;
    }

    /**
     * 获取教师评分TOP10
     */
    @GetMapping("/rank/teacher")
    @ResponseBody
    public List<RankDTO> getTeacherRank() {
        List<RankDTO> list = new ArrayList<>();
//        list.add(new RankDTO(1, "红色记忆", 97.2));
//        list.add(new RankDTO(2, "党的光辉历程", 94.9));
//        list.add(new RankDTO(3, "革命精神永流传", 93.5));
//        list.add(new RankDTO(4, "红色家书", 92.3));
        CompWork queryCompWork = new CompWork();
        queryCompWork.setStatus(1L);
        List<CompWork> workList = compWorkService.selectCompWorkList(queryCompWork);
        workList = workList.stream()
                .sorted(Comparator.comparing(CompWork::getTeacherScore ,
                                Comparator.nullsLast(Comparator.reverseOrder()))
                        .thenComparing(CompWork::getId)) // 得分相同时，按ID排序（可选）
                .limit(10) // 取前10条
                .collect(Collectors.toList()); // 转换为 List


        for (int i = 0; i < workList.size(); i++) {
            CompWork compWork = workList.get(i);
            RankDTO rankDTO = new RankDTO();
            rankDTO.setRank(i+1);
            if(compWork != null && compWork.getTotalScore() != null){
                rankDTO.setScore(compWork.getTotalScore().doubleValue());
            }else{
                rankDTO.setScore(0.0);
            }
            rankDTO.setTitle(compWork.getWorkName());
            list.add(rankDTO);
        }
        // 可继续添加第5-10名数据
        return list;
    }



    /**
     * 获取点赞TOP10
     */
    @GetMapping("/rank/likes")
    @ResponseBody
    public List<RankDTO> getLikesRank() {
        List<RankDTO> list = new ArrayList<>();
        CompWork queryCompWork = new CompWork();
        queryCompWork.setStatus(1L);
        List<CompWork> workList = compWorkService.selectCompWorkList(queryCompWork);

        workList = workList.stream()
                .sorted(Comparator.comparing(CompWork::getLikeCount,
                                Comparator.nullsLast(Comparator.reverseOrder()))
                        .thenComparing(CompWork::getId)) // 点赞数相同时，按ID排序
                .limit(10) // 取前10条
                .collect(Collectors.toList());

        for (int i = 0; i < workList.size(); i++) {
            CompWork compWork = workList.get(i);
            RankDTO rankDTO = new RankDTO();
            rankDTO.setRank(i + 1);
            if (compWork != null && compWork.getLikeCount() != null) {
                rankDTO.setScore(compWork.getLikeCount().doubleValue());
            } else {
                rankDTO.setScore(0.0);
            }
            rankDTO.setCount(compWork.getLikeCount());
            rankDTO.setTitle(compWork.getWorkName());
            list.add(rankDTO);
        }
        return list;
    }

    /**
     * 获取转发TOP10
     */
    @GetMapping("/rank/shares")
    @ResponseBody
    public List<RankDTO> getSharesRank() {
        List<RankDTO> list = new ArrayList<>();
        CompWork queryCompWork = new CompWork();
        queryCompWork.setStatus(1L);
        List<CompWork> workList = compWorkService.selectCompWorkList(queryCompWork);

        workList = workList.stream()
                .sorted(Comparator.comparing(CompWork::getShareCount,
                                Comparator.nullsLast(Comparator.reverseOrder()))
                        .thenComparing(CompWork::getId)) // 转发数相同时，按ID排序
                .limit(10) // 取前10条
                .collect(Collectors.toList());

        for (int i = 0; i < workList.size(); i++) {
            CompWork compWork = workList.get(i);
            RankDTO rankDTO = new RankDTO();
            rankDTO.setRank(i + 1);
            if (compWork != null && compWork.getShareCount() != null) {
                rankDTO.setScore(compWork.getShareCount().doubleValue());
            } else {
                rankDTO.setScore(0.0);
            }
            rankDTO.setCount(compWork.getShareCount());
            rankDTO.setTitle(compWork.getWorkName());
            list.add(rankDTO);
        }
        return list;
    }

    /**
     * 获取浏览TOP10
     */
    @GetMapping("/rank/views")
    @ResponseBody
    public List<RankDTO> getViewsRank() {
        List<RankDTO> list = new ArrayList<>();
        CompWork queryCompWork = new CompWork();
        queryCompWork.setStatus(1L);
        List<CompWork> workList = compWorkService.selectCompWorkList(queryCompWork);

        workList = workList.stream()
                .sorted(Comparator.comparing(CompWork::getLookCount,
                                Comparator.nullsLast(Comparator.reverseOrder()))
                        .thenComparing(CompWork::getId)) // 浏览数相同时，按ID排序
                .limit(10) // 取前10条
                .collect(Collectors.toList());

        for (int i = 0; i < workList.size(); i++) {
            CompWork compWork = workList.get(i);
            RankDTO rankDTO = new RankDTO();
            rankDTO.setRank(i + 1);
            if (compWork != null && compWork.getLookCount() != null) {
                rankDTO.setScore(compWork.getLookCount().doubleValue());
            } else {
                rankDTO.setScore(0.0);
            }
            rankDTO.setCount(compWork.getLookCount());
            rankDTO.setTitle(compWork.getWorkName());
            list.add(rankDTO);
        }
        return list;
    }



}
